<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';

dayjs.extend(utc);
dayjs.extend(timezone);

const route = useRoute();
const router = useRouter();

// Order data
const order = ref({
    id: '',
    total_price: 0,
    real_price: 0,
    order_number: '',
    order_status: 0,
    pay_type: 0,
    order_desc: '',
    pay_time: '',
    created_time: '',
    order_detail: [],
    coupon: {}
});

// Payment modal state
const showPaymentModal = ref(false);
const selectedPayType = ref(1);
const showCountdown = ref(false);
const timeLeft = ref(15 * 60);
let timer = null;

// Constants
const orderStatusMap = {
    0: '待支付',
    1: '已支付',
    2: '已取消',
    3: '已超时'
};

const payTypeMap = {
    0: '微信支付',
    1: '支付宝支付'
};

// Date formatting
const formatToShanghai = (dateString) => {
    if (!dateString) return '';
    return dayjs(dateString).tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
};

// Timer functions
const formatTime = (seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
};

const startTimer = (callback) => {
    timer = setInterval(() => {
        if (timeLeft.value > 0) {
            timeLeft.value--;
        } else {
            clearInterval(timer);
            if (callback) callback();
        }
    }, 1000);
};

const stopTimer = () => {
    if (timer) clearInterval(timer);
};

// Doctor info
const getDoctorInfo = async () => {
    try {
        const doctorId = localStorage.getItem('doctorId');
        if (!doctorId) return;

        const response = await axios.get(`http://127.0.0.1:8000/doctor/docdetail/${doctorId}/`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });
        console.log(response);
        return response.data;
    } catch (error) {
        console.error('Error fetching doctor info:', error);
    }
};

// Navigation
const handleConsultation = () => {
    const doctorId = localStorage.getItem('doctorId');
    if (doctorId) {
        router.push(`/chat-A/${doctorId}`);
    }
};

// Payment handling
const handlePayment = async () => {
    try {
        const textData = JSON.parse(localStorage.getItem('userInputData') || '{}');
        const doctorId = localStorage.getItem('doctorId');
        const selectedCoupon = JSON.parse(localStorage.getItem('selectedCoupon'));

        const response = await axios.post('http://127.0.0.1:8000/orders/orders/', {
            pay_type: selectedPayType.value,
            user_coupon_id: selectedCoupon?.user_coupon_id,
            doctor_id: doctorId,
            discount_name: selectedCoupon?.name || "通用类型"
        }, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (response.data) {
            localStorage.setItem('currentOrder', JSON.stringify(response.data));
            
            if (selectedPayType.value === 1) {
                const paymentResponse = await axios.get(`http://127.0.0.1:8000/pay/alipay/link/?order_id=${response.data.id}`);
                window.open(paymentResponse.data, '_blank');
                showCountdown.value = true;
                startTimer(() => {
                    router.push('/order');
                });
            }
        }
    } catch (error) {
        console.error('Payment error:', error);
    }
};

// Alipay return handling
const handleAlipayReturn = async () => {
    try {
        const searchParams = window.location.search;
        if (!searchParams) return;

        const response = await axios.get(`http://127.0.0.1:8000/pay/alipay/return_result${searchParams}`);
        
        if (response.data) {
            const paymentResult = response.data;
            order.value.pay_time = paymentResult.pay_time;
            order.value.real_price = paymentResult.real_price;
            order.value.order_status = 1;
            
            if (paymentResult.doctor_list) {
                order.value.order_detail = paymentResult.doctor_list.map(doctor => ({
                    ...doctor,
                    doctor_name: doctor.name,
                    doctor_avatar: doctor.avatar
                }));
            }
        }
    } catch (error) {
        console.error('Error processing Alipay return:', error);
    }
};

// Get order details
const getOrderDetails = async () => {
    try {
        const orders = localStorage.getItem('currentOrder');
        const orderId = JSON.parse(orders)?.id;
        if (!orderId) return;

        const response = await axios.get(`http://127.0.0.1:8000/orders/list/?id=${orderId}`, {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (response.data.results && response.data.results.length > 0) {
            order.value = response.data.results[0];
        }
    } catch (error) {
        console.error('Error fetching order:', error);
    }
};

// Lifecycle hooks
watch(
    () => route.query,
    async (newQuery) => {
        if (newQuery.out_trade_no) {
            await handleAlipayReturn();
        }
    },
    { immediate: true }
);

onMounted(async () => {
    await Promise.all([getOrderDetails(), getDoctorInfo()]);
    if (route.query.out_trade_no) {
        await handleAlipayReturn();
    }
});

onUnmounted(() => {
    stopTimer();
});
</script>

<template>
    <div class="order-page">
        <div class="order-container">
            <h1 class="order-title">订单详情</h1>

            <!-- Order Basic Info -->
            <div class="order-section">
                <h2>订单信息</h2>
                <div class="info-grid">
                    <div class="info-item">
                        <span class="label">订单号：</span>
                        <span>{{ order.order_number }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">订单状态：</span>
                        <span :class="['status', `status-${order.order_status}`]">
                            {{ orderStatusMap[order.order_status] }}
                        </span>
                    </div>
                    <div class="info-item">
                        <span class="label">支付方式：</span>
                        <span>{{ payTypeMap[order.pay_type] }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">创建时间：</span>
                        <span>{{ formatToShanghai(order.created_time) }}</span>
                    </div>
                    <div class="info-item" v-if="order.pay_time">
                        <span class="label">支付时间：</span>
                        <span>{{ formatToShanghai(order.pay_time) }}</span>
                    </div>
                </div>
            </div>

            <!-- Doctor Details -->
            <div class="order-section" v-if="order.order_detail.length > 0">
                
                <h2>医生信息</h2>
                <div class="doctor-info" v-for="detail in order.order_detail" :key="detail.id">
                    <img :src="'http://127.0.0.1:8000'+detail.avatar" :alt="detail.doctor_name" class="doctor-avatar">
                    <div class="doctor-details">
                        <h3>{{ detail.doctor_name }}</h3>
                        <p>{{ detail.department }} | {{ detail.get_title_display }}</p>

                        <p>{{ detail.hospital_name }}</p>
                        <hr>
                        <p v-html="detail.introduction"></p>
                    </div>
                </div>
            </div>

            <!-- Price Summary -->
            <div class="order-section">
                <h2>价格详情</h2>
                <div class="price-summary">
                    <div class="price-item">
                        <span>订单总价：</span>
                        <span>¥{{ order.total_price }}</span>
                    </div>
                    <div class="price-item" v-if="order.coupon.name">
                        <span>优惠券：</span>
                        <span>{{ order.coupon.name }}</span>
                    </div>
                    <div class="price-item total">
                        <span>实付金额：</span>
                        <span>¥{{ order.real_price }}</span>
                    </div>
                </div>
            </div>

            <!-- Consultation Button -->
            <div class="consultation-button-container">
                <button class="consultation-button" @click="handleConsultation">
                    继续问医生
                </button>
            </div>

            <!-- Payment Modal -->
            <div v-if="showPaymentModal" class="modal-overlay">
                <div class="modal-content">
                    <h2>选择支付方式</h2>
                    <div v-if="showCountdown" class="countdown-timer">
                        支付倒计时: {{ formatTime(timeLeft) }}
                    </div>
                    <div class="payment-options">
                        <div class="payment-option" :class="{ active: selectedPayType === 1 }"
                            @click="selectedPayType = 1">
                            <img src="https://tse4.mm.bing.net/th?id=OIP.lxDbWrNtZ7lMSR_p-xIjqwHaHa&pid=Api"
                                alt="支付宝" />
                            <span>支付宝支付</span>
                        </div>
                        <div class="payment-option" :class="{ active: selectedPayType === 0 }"
                            @click="selectedPayType = 0">
                            <img src="https://tse4.mm.bing.net/th?id=OIP.KX_05K6jrKo-yU66jG3mNwHaFo&pid=Api" alt="微信" />
                            <span>微信支付</span>
                        </div>
                    </div>
                    <div class="price-display">
                        支付金额：<span class="amount">¥{{ order.real_price }}</span>
                    </div>
                    <div class="modal-actions">
                        <button class="cancel-btn" @click="showPaymentModal = false">取消</button>
                        <button class="confirm-btn" @click="handlePayment">确认支付</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
.order-page {
    padding: 2rem;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.order-container {
    max-width: 800px;
    margin: 0 auto;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 2rem;
}

.order-title {
    text-align: center;
    margin-bottom: 2rem;
    color: #333;
}

.order-section {
    margin-bottom: 2rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid #eee;
}

.order-section h2 {
    color: #333;
    margin-bottom: 1rem;
    font-size: 1.2rem;
}

.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1rem;
}

.info-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.label {
    color: #666;
    min-width: 80px;
}

.status {
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.9rem;
}

.status-0 {
    background-color: #fff3cd;
    color: #856404;
}

.status-1 {
    background-color: #d4edda;
    color: #155724;
}

.status-2 {
    background-color: #f8d7da;
    color: #721c24;
}

.status-3 {
    background-color: #cce5ff;
    color: #004085;
}

.doctor-info {
    display: flex;
    gap: 1rem;
    padding: 1rem;
    background-color: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 1rem;
}

.doctor-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
}

.doctor-details {
    flex: 1;
}

.doctor-details h3 {
    margin: 0 0 0.5rem 0;
    color: #333;
}

.doctor-details p {
    margin: 0.25rem 0;
    color: #666;
}

.price-summary {
    background-color: #f8f9fa;
    padding: 1rem;
    border-radius: 8px;
}

.price-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
}

.price-item.total {
    margin-top: 1rem;
    padding-top: 1rem;
    border-top: 1px solid #dee2e6;
    font-weight: bold;
    color: #dc3545;
}

.consultation-button-container {
    text-align: center;
    margin-top: 2rem;
}

.consultation-button {
    background-color: #00b578;
    color: white;
    padding: 12px 32px;
    border-radius: 24px;
    font-size: 16px;
    font-weight: 500;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s;
}

.consultation-button:hover {
    background-color: #00a067;
}

/* Payment Modal Styles */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    padding: 24px;
    border-radius: 12px;
    width: 90%;
    max-width: 400px;
}

.countdown-timer {
    text-align: center;
    margin: 12px 0;
    padding: 8px;
    background-color: #fff3cd;
    color: #856404;
    border-radius: 4px;
    font-weight: bold;
}

.payment-options {
    display: flex;
    gap: 16px;
    margin: 24px 0;
}

.payment-option {
    flex: 1;
    padding: 16px;
    border: 2px solid #eee;
    border-radius: 8px;
    display: flex;
    align-items: center;
    gap: 12px;
    cursor: pointer;
    transition: all 0.3s;
}

.payment-option.active {
    border-color: #00b578;
    background-color: #f0fff9;
}

.payment-option img {
    width: 32px;
    height: 32px;
    object-fit: cover;
}

.modal-actions {
    display: flex;
    gap: 16px;
    justify-content: flex-end;
    margin-top: 24px;
}

.cancel-btn, .confirm-btn {
    padding: 8px 24px;
    border-radius: 20px;
    border: none;
    cursor: pointer;
}

.cancel-btn {
    background-color: #f5f5f5;
    color: #666;
}

.confirm-btn {
    background-color: #00b578;
    color: white;
}
</style>